//JsonTest.java
package com.ylaihui.json;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.Test;

import java.beans.PersistenceDelegate;
import java.time.Period;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lisimmy www.ylaihui.com
 * @create 2021-08-06
 */
public class JsonTest {

    @Test
    public void test1(){
        //JavaBean 到 JSON的转换
        Order order = new Order(1, "order1", 12.22);

        Gson gson = new Gson();

        String s = gson.toJson(order);
        System.out.println(s);

        // JSON 到 JavaBean的转换

        Order order1 = gson.fromJson(s, Order.class);
        System.out.println(order1);


    }

    @Test
    public void test2(){
        //List 到 JSON的转换
        List<Order> orders = new ArrayList<>();
        orders.add(new Order(1, "order1", 11.11));
        orders.add(new Order(2, "order2", 22.22));
        orders.add(new Order(3, "order3", 33.33));

        Gson gson = new Gson();
        String s = gson.toJson(orders);
        System.out.println(s);

        // JSON 到 List 的转换
        List<Order> o = gson.fromJson(s, new OrderListType().getType());
        Order order = o.get(1);
        System.out.println(o);
        System.out.println(order);


    }

    @Test
    public void test3(){
        //Map 到 JSON 的转换
        Map<Integer, Order> orderMap = new HashMap<Integer, Order>();
        orderMap.put(1, new Order(1, "order1", 11.11));
        orderMap.put(1, new Order(2, "order2", 22.22));
        Gson gson = new Gson();

        String s = gson.toJson(orderMap);
        System.out.println(s);

        // JSON 到 Map 的转换
        // Map<Integer, Order> o = gson.fromJson(s, new OrderMapType().getType());
        // 匿名类
        Map<Integer, Order> o = gson.fromJson(s, new TypeToken<HashMap<Integer, Order>>(){}.getType());
        System.out.println(o);
        Order order = o.get(1);
        System.out.println(order);
    }
}
